package com.dede.state;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

/**
 * @author hsh
 *         2018/1/22 18:17.
 */
class StateUtil {

    private StateUtil() {
    }

    /**
     * 查找ContentView和ContentParent
     *
     * @param obj Activity View
     * @return
     */
    static TargetContent findTargetContent(Object obj) {
        ViewGroup contentParent;// content的父布局
        Context context;
        if (obj instanceof Activity) {
            Activity activity = (Activity) obj;
            context = activity;
            contentParent = activity.findViewById(android.R.id.content);
        } else if (obj instanceof View) {
            View view = (View) obj;
            contentParent = (ViewGroup) (view.getParent());
            context = view.getContext();
        } else {
            // 必须为这三种类型
            throw new IllegalArgumentException("The target must be within Activity, Fragment, View.");
        }

        int childIndex = 0;// contentView所在parent的索引
        View oldContent;// ContentView
        // 如果是Activity，contentParent不为空，其他情况均为空
        int childCount = contentParent == null ? 0 : contentParent.getChildCount();
        if (obj instanceof View) {
            oldContent = (View) obj;
            for (int i = 0; i < childCount; i++) {
                if (contentParent.getChildAt(i) == oldContent) {
                    childIndex = i;
                    break;
                }
            }
        } else {
            oldContent = contentParent != null ? contentParent.getChildAt(0) : null;
        }

        if (oldContent == null) {
            throw new IllegalArgumentException(String.format("enexpected error when register LoadSir in %s", obj
                    .getClass().getSimpleName()));
        }

        return new TargetContent(context, oldContent, childIndex, contentParent);
    }
}
